package com.lang.datahandler.utils;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;
import com.lang.constrants.DatasourceConstrants;
import com.lang.dto.datasource.BaseDataSourceDto;
import com.lang.enums.DataSourceEnum;
import com.lang.exception.BaseException;
import com.lang.exception.datasource.DataSourceExceptionEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;


/**
 * creat by SimonLang
 * 2022/12/31 17:29
 */
@Slf4j
@Component
public class DynamicDataSource {

    // DruidDatasource的初始化
    private static DruidDataSource dataSource = new DruidDataSource();
    static {
        dataSource.setMaxActive(20);
        dataSource.setInitialSize(5);
        // 检测连接的是否有效的时间
        dataSource.setValidationQueryTimeout(3);
        dataSource.setTimeBetweenEvictionRunsMillis(60000);
    }

    // 使用单例模式（连接池只需要一个即可）
    private static final DynamicDataSource dynamicDataSource = new DynamicDataSource();

    private DynamicDataSource(){

    }

    public static DynamicDataSource getInstance(){
        return dynamicDataSource;
    }


    /**
     * 测试连接
     * @param url
     * @param baseDataSourceDto
     * @return
     */
    public DruidPooledConnection connect(String url, BaseDataSourceDto baseDataSourceDto){
        dataSource.setUrl(url);
        dataSource.setUsername(baseDataSourceDto.getDbUsername());
        dataSource.setPassword(baseDataSourceDto.getDbPassword());

        String dataSourceType = baseDataSourceDto.getDataSourceType();
        if(DataSourceEnum.MYSQL.getType().equals(dataSourceType)){
            dataSource.setValidationQuery(DatasourceConstrants.MYSQL_VALIDATION_QUERY);
        }
        else if(DataSourceEnum.ORACLE.getType().equals(dataSourceType)){
            dataSource.setValidationQuery(DatasourceConstrants.ORACLE_VALIDATION_QUERY);
        }
        try {
            return dataSource.getConnection();
        }catch (Exception e){
            log.error("数据源连接异常:{}",e);
            throw new BaseException(DataSourceExceptionEnum.CONNECTION_EXCEPTION.getCode(),DataSourceExceptionEnum.CONNECTION_EXCEPTION.getMessage());
        }
    }



}

